<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-tabs v-model="activeName">
        <el-tab-pane label="角色管理" name="first">
          <!-- 新增角色按钮 -->
          <el-row style="height: 60px">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="addRole"
            >添加角色</el-button>
          </el-row>
          <!-- 表格 -->
          <el-table :data="list" border="" style="width: 100%">
            <el-table-column
              type="index"
              label="序号"
              width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="角色名称"
              width="240"
              prop="name"
              align="center"
            >
            </el-table-column>
            <el-table-column label="描述" prop="description" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template v-slot="{ row }">
                <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteRole(row.id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <!-- 分页组件 -->
            <el-pagination
              layout="prev,pager,next"
              :page-size="page.pagesize"
              :total="page.total"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="second">
          <el-alert
            title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
            type="info"
            show-icon
            :closable="false"
          />
          <el-form label-width="120px" style="margin-top: 50px">
            <el-form-item label="公司名称">
              <el-input v-model="formData.name" disabled style="width: 400px" />
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input
                v-model="formData.companyAddress"
                disabled
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input
                v-model="formData.mailbox"
                disabled
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                :rows="3"
                disabled
                style="width: 400px"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 弹层 -->
    <el-dialog
      :visible="showDialog"
      v-bind="$attrs"
      :title="roleForm.id?'编辑角色':'新增角色'"
      v-on="$listeners"
      @open="onOpen"
      @close="onClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        size="medium"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            placeholder="请输入角色描述"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </el-row>
    </el-dialog>

    <!-- 分配权限的弹层 -->
    <el-dialog title="分配权限" :visible="showPermDialog" @close="closePerm">
      <el-tree
        ref="treeRef"
        :data="permData"
        :props="{label:'name'}"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
        :default-checked-keys="selectCheck"
      >
      </el-tree>
      <el-row slot="footer" type="flex" justify="center">
        <el-button @click="closePerm">取消</el-button>
        <el-button type="primary" @click="handelPermConfirm">确认</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { addRole, assignPerm, deleteRole, getCompanyInfo, getRoleDetail, getRoleList, updateRole } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Setting',
  components: {},
  props: {},
  data() {
    return {
      activeName: 'first',
      list: [],
      page: {
        // 放置页码及相关数据
        page: 1,
        pagesize: 10,
        total: 0 // 记录总数
      },
      formData: {},
      showDialog: false,
      roleForm: {
        name: undefined,
        description: undefined
      },
      rules: {
        name: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
        description: []
      },
      showPermDialog: false, // 控制对话框显示的弹层
      permData: [], // 接收权限--保存数据
      selectCheck: [], // 选中权限的ids
      roleId: undefined
    }
  },
  async created() {
    this.getRoleList()
    const res = await getCompanyInfo(this.$store.state.user.userInfo.companyId)
    this.formData = res
  },
  mounted() {},
  methods: {
    // 分配权限
    async assignPerm(id) {
      this.roleId = id // 保存当前行的角色id
      this.permData = tranListToTreeData(await getPermissionList(), '0')
      // 获取权限的ids
      const { permIds } = await getRoleDetail(id)
      this.selectCheck = permIds.map(t => t instanceof Object ? t.id : t)
      this.showPermDialog = true
    },
    closePerm() {
      this.selectCheck = []
      this.showPermDialog = false
    },
    async handelPermConfirm() {
      // 发请求
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.closePerm()
    },
    // 新增角色
    addRole() {
      this.showDialog = true
    },
    // 编辑角色
    async editRole(id) {
      // 实现数据回写
      this.roleForm = await getRoleDetail(id)
      // 打开弹层
      this.showDialog = true
    },
    onOpen() {},
    onClose() {
      this.close()
    },
    close() {
      // 方式一
      // this.roleForm={
      //    name: undefined,
      //   description: undefined
      // }
      // 方式二
      this.roleForm = this.$options.data().roleForm
      this.$refs['roleFormRef'].resetFields()
      this.showDialog = false
    },
    handelConfirm() {
      // 表单校验
      this.$refs['roleFormRef'].validate(async valid => {
        if (!valid) return
        // 发请求
        if (this.roleForm.id) {
          // 编辑
          await updateRole(this.roleForm)
        } else {
          // 新增
          await addRole(this.roleForm)
        }
        this.$message.success('操作成功')
        // 刷新
        this.getRoleList()
        this.close()
      })
    },
    async deleteRole(id) {
      try {
        await this.$confirm('是否删除')
        // 点击了是,发请求
        await deleteRole(id)
        this.$message.success('删除成功')
        this.getRoleList()
      } catch (error) {
        // 点击否
        console.log('删除角色失败')
      }
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.getRoleList()
    },
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page)
      this.page.total = total
      this.list = rows
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
